from django.db import models
from django.utils import timezone

class ChatSession(models.Model):
    """聊天会话模型"""
    session_id = models.CharField(max_length=100, unique=True, help_text='会话ID')
    user_id = models.BigIntegerField(null=True, blank=True, help_text='用户ID')
    start_time = models.DateTimeField(default=timezone.now, help_text='会话开始时间')
    last_activity = models.DateTimeField(default=timezone.now, help_text='最后活动时间')
    is_active = models.BooleanField(default=True, help_text='会话是否活跃')
    
    class Meta:
        db_table = 'tb_chat_session'
        verbose_name = '聊天会话'
        verbose_name_plural = '聊天会话'
        managed = False
        app_label = 'chatbot'
    
    def __str__(self):
        return f"会话 {self.session_id} - 用户 {self.user_id or '游客'}"

class ChatMessage(models.Model):
    """聊天消息模型"""
    message_id = models.BigAutoField(primary_key=True, help_text='消息ID')
    session_id = models.ForeignKey(ChatSession, on_delete=models.CASCADE, db_column='session_id', related_name='messages', help_text='所属会话')
    role = models.CharField(max_length=20, help_text='消息角色(user/assistant)')
    content = models.TextField(help_text='消息内容')
    timestamp = models.DateTimeField(default=timezone.now, help_text='消息时间')
    
    class Meta:
        db_table = 'tb_chat_message'
        verbose_name = '聊天消息'
        verbose_name_plural = '聊天消息'
        managed = False
        app_label = 'chatbot'
    
    def __str__(self):
        return f"{self.role}: {self.content[:30]}..."
